<!--
 * @Author: lihaogn
 * @Date: 2021-08-20 07:46:20
 * @LastEditTime: 2021-08-29 15:04:15
 * @LastEditor: lihaogn
 * @Description: 弹出框
 * @FilePath: \lix-management\src\components\common\lix-popover\index.vue
-->
<template>
  <!-- :id="tooltipId" -->
  <div class="lix-popover">
    <div ref="wrapper">
      <slot name="reference"></slot>
    </div>

    <div
      ref="lixContextMenu"
      class="menu-box"
      v-show="visible"
      :style="{ width: width }"
    >
      <slot></slot>
    </div>
  </div>
</template>
<script>
// import { generateId } from "@/utils/util";
export default {
  name: 'lix-popover',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: '100px'
    }
  },
  data() {
    return {}
  },
  computed: {
    // tooltipId() {
    //   return `lix-popover-${generateId()}`;
    // }
  },
  created() {},
  mounted() {
    // 点击弹窗之外的地方关闭弹窗
    document.addEventListener('click', e => {
      this.closeMenu(e, this.$refs.lixContextMenu)
    })
    // 右击关闭非当前点击对象引起的弹窗
    document.addEventListener('contextmenu', e => {
      this.closeMenu(e, this.$refs.wrapper.children[0])
    })
    // 点击了一个操作后关闭弹窗
    this.$refs.lixContextMenu.children[0].addEventListener('click', e => {
      this.onClickClose(e)
    })
  },
  updated() {},
  beforeDestroy() {
    document.removeEventListener('click', e => {
      this.closeMenu(e)
    })
    document.removeEventListener('contextmenu', e => {
      this.closeMenu(e, this.$refs.wrapper.children[0])
    })
    this.$refs.lixContextMenu.children[0].removeEventListener('click', e => {
      this.onClickClose(e)
    })
  },
  methods: {
    /**
     * @author: lihaogn
     * @Date: 2021-08-21 17:26:55
     * @description: 点击弹窗之外的地方关闭弹窗
     * @param {*} e - event
     * @param {*} el - 需要操作的element
     * @return {*}
     */
    closeMenu(e, el) {
      e.stopPropagation()
      if (el) {
        if (!el.contains(e.target)) {
          this.$emit('update:visible', false)
        }
      }
    },
    /**
     * @author: lihaogn
     * @Date: 2021-08-21 17:27:17
     * @description: 点击了一个操作后关闭弹窗
     * @param {*} e - event
     * @return {*}
     */
    onClickClose(e) {
      e.stopPropagation()
      this.$emit('update:visible', false)
    }
  }
}
</script>
<style lang="less" scoped>
.lix-popover {
  position: relative;

  .menu-box {
    position: absolute;
    margin-top: 10px;
    padding: 10px 12px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.4);
    background: #fff;
    z-index: 999;
    box-sizing: border-box;
  }
}
</style>
